import { defineStore } from 'pinia';
import { getOrgTree } from '/@/api/manage/manage.ts';

export const useStaffInfoStore = defineStore('StaffInfoSotre', {
	state: () => ({
		treeData: [Array] as any[], //员工股组织树数据
		departmentData: [Array] as any[], //部门列表数据
		departmentShowData: [Array] as any[], //部门列表展示给select的数据
		totalDepartmentData: [Array] as any[], //将各个组织数据放到一个数组中
		// url: 'http://120.24.28.68:39009/api/', //store中设置url值
		url: 'http://202.104.182.126:39009/api/',
	}),

	actions: {
		//请求组织树数据
		async loadTreeData() {
			// if (this.treeData[0].constructor === Object) {
			// 	return;
			// }
			const departMent: any[] = [];
			const res = await getOrgTree({
				Type: 1,
			});
			console.log('res', res);
			this.totalDepartmentData = [];
			const totalArray: any[] = [];
			//递归遍历数组, 对数组中的每一个对象进行指定操作
			function formatRoutes(routerArr: any[]) {
				const arr: any[] = [];
				//部门-组织列表中的最后一级拼接而成的数组

				let obj = {};
				routerArr.forEach((router) => {
					const tmp = { ...router };
					if (tmp.children) {
						tmp.children = formatRoutes(tmp.children);
						//指定操作将tmp.title 替换为tmp.label
						obj = {
							id: tmp.id,
							parentId: tmp.parentId,
							label: tmp.title,
							value: tmp.value,
							weight: tmp.weight,
							children: tmp.children,
							//设置指定层级
							disabled: tmp.weight == 1,
						};
						// obj = tmp;
						arr.push(obj);
						totalArray.push(obj);
						//遍历获取children最后一层元素
						if (tmp.children.length == 0) {
							departMent.push(obj);
						}
					}
				});
				return arr;
			}
			let treeDataArray = formatRoutes(res.data);
			this.departmentData = departMent;
			this.treeData = treeDataArray;
			this.totalDepartmentData = totalArray;

			const showDepartMent: any[] = [];
			for (let i = 0; i < this.departmentData.length; i++) {
				const currentObj = this.departmentData[i];
				let showObj = {
					label: currentObj.label,
					value: i,
				};
				showDepartMent.push(showObj);
			}
			this.departmentShowData = showDepartMent;
		},
	},
});
